package com.wmh.baseservice.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdAutho;
import com.wmh.baseservice.admin.pojo.AdInfo;
import com.wmh.baseservice.admin.pojo.AdRolePermissions;
import com.wmh.baseservice.admin.service.AdAuthoService;
import com.wmh.baseservice.admin.service.AdInfoService;
import com.wmh.baseservice.admin.service.AdRolePermissionsService;
import com.wmh.baseservice.admin.service.AdRoleService;
import com.wmh.baseservice.admin.tools.enums.AdInfoStatus;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.annotation.repeat.PreventRepeat;
import com.wmh.baseservice.common.config.KeyConfig;
import com.wmh.baseservice.common.mybatisplus.structure.CustomQueryWrapper;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.ShiroMd5Util;
import com.wmh.baseservice.common.utils.encrypt.RSAUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author mmx generator
 * @since 2021-02-03
 */
@Api(tags = "管理员-账号信息相关接口")
@RestController
@RequestMapping("admin/adInfo")
@RequiresRoles("admin")
public class AdInfoController {
    @Resource
    private HttpServletRequest request;
    @Resource
    private AdInfoService adInfoService;
    @Resource
    private AdRolePermissionsService adRolePermissionsService;



    @ApiOperation("账号列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "account", value = "账号", required = false),
    })
    @PostMapping("list")
    public String list(PageInfo pageInfo, String account) {
//         执行分页辅助工具
        PageResult<AdInfo> pageResult = new PageUtil<AdInfo>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(account)) {
                queryWrapper.eq(AdAutho.ACCOUNT, account);
            }
            queryWrapper.select(AdInfo.getFields(AdInfo.SALT));
            adInfoService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item->{
            AdRolePermissions adRolePermissions = adRolePermissionsService.getByIdForUpdate(item.getRoleId());
            item.setRoleName(adRolePermissions.getRole());
        });
        return ReturnBody.success(pageResult);
    }


    @ApiOperation("添加账号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "account", value = "账号", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "roleId", value = "角色ID（成员类型）", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "password", value = "密码", required = false),
    })
    @PostMapping("add")
    @PreventRepeat
    public String add(String account, String password, Long roleId,String name) throws Exception {
        Long id = (Long) request.getAttribute(AdInfo.ID);
        if (id != 1) {
            return ReturnBody.error("只有超级管理员可以添加或编辑账号");
        }
        password= RSAUtil.decryptByPrivateKey(password,RSAUtil.PRIVATE_KEY);
        QueryWrapper<AdInfo> queryWrapper = new CustomQueryWrapper<AdInfo>().eq(AdInfo.ACCOUNT, account);
        AdInfo adInfo = adInfoService.getOne(queryWrapper);
        if (null != adInfo) {
            return ReturnBody.error("该账号已存在");
        }
        String salt = ShiroMd5Util.createSalt();
        AdInfo  adInfoTemp= new AdInfo().setAccount(account).setPassword(ShiroMd5Util.encodePwd(password+ KeyConfig.SHIRO_SALE,salt)).setRoleId(roleId).setSalt(salt);
        if (CommUtil.checkNull(name)){
            adInfoTemp.setName(name);
        }
        adInfoService.add(adInfoTemp);
        return ReturnBody.success();
    }

    @ApiOperation("修改账号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "管理员id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "account", value = "账号", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "roleId", value = "角色ID（成员类型）", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "password", value = "密码", required = false),
    })
    @PostMapping("update")
    @ParameterVerify(notNull = "roleId")
    public String add(Long id, String account, String password, Long roleId,String name) throws Exception {
        Long adId = (Long) request.getAttribute(AdInfo.ID);
        if (adId != 1) {
            return ReturnBody.error("只有超级管理员可以添加或编辑账号");
        }
        if (CommUtil.checkNull(password)){
            password=RSAUtil.decryptByPrivateKey(password,RSAUtil.PRIVATE_KEY);
        }
        QueryWrapper<AdInfo> queryWrapper = new CustomQueryWrapper<AdInfo>().eq(AdInfo.ACCOUNT, account);
        AdInfo adInfo = adInfoService.getOne(queryWrapper);

        AdInfo adInfoTemp = adInfoService.getOneForUpdate(new QueryWrapper<AdInfo>().eq(AdInfo.ID, id));
        if (!CommUtil.checkNull(adInfoTemp)){
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (null != adInfo&&!account.equals(adInfoTemp.getAccount())) {
            return ReturnBody.error("该账号已存在");
        }
        adInfoTemp.setAccount(account).setRoleId(roleId);
        if (CommUtil.checkNull(password)){
            adInfoTemp.setPassword(ShiroMd5Util.encodePwd(password+KeyConfig.SHIRO_SALE,adInfoTemp.getSalt()));
        }
        if (CommUtil.checkNull(name)){
            adInfoTemp.setName(name);
        }
        adInfoService.updateInfo(adInfoTemp);
        return ReturnBody.success();
    }


    @ApiOperation("删除账号")
    @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "id", value = "账号ID", required = true)
    @PostMapping("delete")
    @ParameterVerify(notNull = "id")
    public String delete(Long id) {
        return adInfoService.delete(id);
    }


    @ApiOperation("冻结或解冻操作")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "id", value = "账号ID", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "status", value = "账号状态 0正常，-1冻结", required = true)
    })
    @PostMapping("freezeOrThaw")
    @ParameterVerify(notNull = {"id", "status"})
    public String freezeOrThaw(Long id, Integer status) {
        if (!status.equals(AdInfoStatus.FREEZE.getValue()) && !status.equals(AdInfoStatus.NORMAL.getValue())) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        AdInfo adInfo = new AdInfo()
                .setId(id)
                .setStatus(status);
        if (!adInfoService.updateById(adInfo)) {
            return ReturnBody.error();
        }
        return ReturnBody.success();
    }


}
